public class BinarySearchTree {


    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    public boolean search(int val) {
        if(root == null) {
            return false;
        }
        TreeNode cur = root;
        while (cur != null) {
            if(cur.val < val) {
                cur = cur.right;
            }else if(cur.val >val) {
                cur = cur.left;
            }else {
                return true;
            }
        }
        return false;
    }


    public void insert(int val) {
        if(root == null) {
            root = new TreeNode(val);
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur != null) {
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                //一样的值 不进行存储
                return;
            }
        }
        TreeNode newNode = new TreeNode(val);
        if(parent.val > val) {
            parent.left = newNode;
        }else {
            parent.right = newNode;
        }
    }

    public void remove(int val) {
        TreeNode cur = root;
        TreeNode parent = null;

        while (cur != null) {
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                //开始删除了
                removeNode(cur,parent);
                return;
            }
        }
    }

    /**
     * 删除节点
     * @param cur 要删除的节点
     * @param parent 要删除的节点的父亲节点
     */
    private void removeNode(TreeNode cur, TreeNode parent) {
        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            }else if(cur == parent.left) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            }else if(cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            TreeNode target = cur.right;
            TreeNode targetParent = cur;

            while (target.left != null) {
                targetParent = target;
                target = target.left;
            }
            //开始替换值
            cur.val = target.val;
            //删除
            if(target == targetParent.right) {
                targetParent.right = target.right;
            }else {
                targetParent.left = target.right;
            }
        }
    }


}
